/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.minierp.bean.EstablishmentBean;
import com.minierp.bean.EstablishmentContactBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.AreaDao;
import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.EstablishmentContactDao;
import com.minierp.dao.EstablishmentDao;
import com.minierp.dao.EstablishmentLevelDao;
import com.minierp.dao.EstablishmentTypeDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.SerialNumberDao;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.Establishment;
import com.minierp.model.EstablishmentContact;
import com.minierp.model.EstablishmentLog;
import com.minierp.model.TallySet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class EstablishmentFormCtr extends SimpleFormController {
	private EstablishmentTypeDao establishmentTypeDao;
	private EstablishmentLevelDao establishmentLevelDao;
	private AreaDao areaDao;
	private EstablishmentContactDao establishmentContactDao;
	private EstablishmentDao establishmentDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private IdGenerator idGenerator;

	protected Map referenceData(HttpServletRequest request) throws Exception {
		HashMap refData = new HashMap();
		String id = request.getParameter("id");
		if (id == null) {
			id = "";
		}

		refData.put("id", id);
		String showTag = request.getParameter("show_tag");
		if (showTag == null) {
			showTag = "";
		}

		refData.put("showTag", showTag);
		String type = request.getParameter("type");
		refData.put("type", type);
		if (type == null || type.equals("CLIENT")) {
			refData.put("estTypeList", this.establishmentTypeDao.getList(true));
			refData.put("estLevelList",
					this.establishmentLevelDao.getList(true));
		}

		refData.put("areaList", this.areaDao.getList(true));
		refData.put("doRefresh", request.getParameter("do_refresh"));
		return refData;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = request.getParameter("id");
		String type = request.getParameter("type");
		CodeRule cr = this.codeRuleDao.get(type);
		if (cr == null) {
			throw new Exception("Code rule not found for establishment");
		} else {
			EstablishmentBean form = new EstablishmentBean();
			form.setCodeRule(cr);
			ArrayList arr = new ArrayList();
			Establishment establishment;
			int i;
			EstablishmentContactBean cb;
			EstablishmentContact c;
			if (id != null && !id.equals("")) {
				establishment = (Establishment) this.establishmentDao.get(
						Establishment.class, Long.parseLong(id));
				form.setEstablishment(establishment);
				if (establishment == null) {
					throw new Exception("Record not found for id:" + id);
				}

				if (establishment.getSuperiorId() != 0L) {
					Establishment arg11 = (Establishment) this.establishmentDao
							.get(Establishment.class,
									establishment.getSuperiorId());
					if (arg11 != null) {
						form.setSuperiorName(arg11.getEstName());
						establishment.setSuperiorId(arg11.getId());
					}
				}

				if (establishment.getTallySetId() != 0L) {
					TallySet arg12 = (TallySet) this.establishmentDao.get(
							TallySet.class, establishment.getTallySetId());
					if (arg12 != null) {
						form.setTallySetName(arg12.getTitle());
					}
				}

				List arg13 = this.establishmentContactDao.getList(establishment
						.getId());

				for (i = 0; i < arg13.size(); ++i) {
					cb = new EstablishmentContactBean();
					c = (EstablishmentContact) arg13.get(i);
					cb.setEstablishmentContact(c);
					cb.setStatus("UNCHANGE");
					cb.setOldId(c.getId());
					arr.add(cb);
				}

				form.setContacts(arr);
			} else {
				if (type.equals("CLIENT")) {
					if (!EncCommonHelper.checkPrivilege(request, "BASE_CLIE")
							&& !EncCommonHelper.checkPrivilege(request,
									"BUSI_CLIE")) {
						throw new PermissionDennyException("Permission Denny");
					}
				} else if (type.equals("COOPERATOR")) {
					if (!EncCommonHelper.checkPrivilege(request, "BASE_COOP")
							&& !EncCommonHelper.checkPrivilege(request,
									"COOP_COOP")) {
						throw new PermissionDennyException("Permission Denny");
					}
				} else if (!EncCommonHelper
						.checkPrivilege(request, "BASE_PROV")
						&& !EncCommonHelper
								.checkPrivilege(request, "PURC_PROV")) {
					throw new PermissionDennyException("Permission Denny");
				}

				establishment = new Establishment();
				form.setEstablishment(establishment);
				form.getEstablishment().setEstType(type);
				UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
				establishment.setManagerId(ub.getStaffer().getId());
				establishment.setManagerName(ub.getStaffer().getStafferName());
				establishment.setCreaterId(ub.getStaffer().getId());
				establishment.setCreaterName(ub.getStaffer().getStafferName());
				establishment.setTallySetId(ub.getUser().getDfTsId());
				form.setTallySetName(ub.getDfTsName());

				for (i = 0; i < 3; ++i) {
					cb = new EstablishmentContactBean();
					c = new EstablishmentContact();
					cb.setEstablishmentContact(c);
					arr.add(cb);
				}

				form.setContacts(arr);
			}

			return form;
		}
	}

	protected void onBind(HttpServletRequest request, Object command)
			throws Exception {
		EstablishmentBean form = (EstablishmentBean) command;
		int num = Integer.parseInt(request.getParameter("contact_num"));
		ArrayList arr = new ArrayList();
		boolean foundFirstContact = false;

		for (int i = 0; i < num; ++i) {
			EstablishmentContactBean cb = new EstablishmentContactBean();
			EstablishmentContact c = new EstablishmentContact();
			c.setContactName(request.getParameter("contact_name_" + i));
			c.setEmail(request.getParameter("email_" + i));
			c.setIm(request.getParameter("im_" + i));
			c.setMark(request.getParameter("mark_" + i));
			c.setMobile(request.getParameter("mobile_" + i));
			c.setPhone(request.getParameter("phone_" + i));
			c.setPossie(request.getParameter("possie_" + i));
			c.setSex(request.getParameter("sex_" + i));
			if (request.getParameter("is_main_" + i) != null
					&& request.getParameter("is_main_" + i).equals("1")) {
				c.setIsMain("Y");
			} else {
				c.setIsMain("N");
			}

			if (request.getParameter("id_" + i) != null
					&& !request.getParameter("id_" + i).equals("")) {
				c.setId(Long.parseLong(request.getParameter("id_" + i)));
				cb.setOldId(c.getId());
			}

			cb.setEstablishmentContact(c);
			cb.setStatus(request.getParameter("status_" + i));
			arr.add(cb);
			if (!foundFirstContact && !cb.getStatus().equals("DELETE")
					&& c.getContactName() != null
					&& !c.getContactName().equals("")) {
				form.getEstablishment().setLinkman(c.getContactName());
				form.getEstablishment().setLinkmanPhone(c.getMobile());
				foundFirstContact = true;
			}
		}

		if (!foundFirstContact) {
			form.getEstablishment().setLinkman("");
			form.getEstablishment().setLinkmanPhone("");
		}

		form.setContacts(arr);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		String id = request.getParameter("id");
		String alertMsg = "";
		EstablishmentBean form = (EstablishmentBean) command;
		Establishment obj = form.getEstablishment();
		obj.setNameSpell(PageHelper.getPinYinHeadChar(obj.getEstName())
				.toUpperCase());
		String oldSuperiorIdStr = "";
		if (obj.getSuperiorIdStr() != null
				&& !obj.getSuperiorIdStr().equals("")) {
			oldSuperiorIdStr = obj.getSuperiorIdStr();
		}

		String superiorIdStr = "";
		if (obj.getSuperiorId() != 0L) {
			Establishment estChange = (Establishment) this.establishmentDao
					.get(Establishment.class, obj.getSuperiorId());
			if (estChange != null) {
				if (estChange.getSuperiorIdStr() != null
						&& !estChange.getSuperiorIdStr().equals("")) {
					superiorIdStr = estChange.getSuperiorIdStr()
							+ estChange.getId() + ";";
				} else {
					superiorIdStr = ";" + estChange.getId() + ";";
				}
			}
		}

		obj.setSuperiorIdStr(superiorIdStr);
		boolean arg22 = false;
		EstablishmentLog log = new EstablishmentLog();
		Object oldContList = new ArrayList();
		String alertType;
		String type;
		String continueFlag;
		if (id != null && !id.equals("")) {
			if (obj.getEstType().equals("CLIENT")) {
				Object[] arg23 = this.establishmentDao.getStatusValues(obj
						.getId());
				String mv = "";
				alertType = "";
				type = "";
				continueFlag = "";
				String nName = "";
				String nPhone = "";
				String nEmail = "";
				String nAddress = "";
				if (arg23[0] != null) {
					mv = arg23[0].toString();
				}

				if (arg23[1] != null) {
					alertType = arg23[1].toString();
				}

				if (arg23[2] != null) {
					type = arg23[2].toString();
				}

				if (arg23[3] != null) {
					continueFlag = arg23[3].toString();
				}

				if (obj.getEstName() != null) {
					nName = obj.getEstName();
				}

				if (obj.getPhone() != null) {
					nPhone = obj.getPhone();
				}

				if (obj.getEmail() != null) {
					nEmail = obj.getEmail();
				}

				if (obj.getAddress() != null) {
					nAddress = obj.getAddress();
				}

				if (!mv.equals(nName)) {
					log.setEstName(mv + " --> " + nName);
					arg22 = true;
				}

				if (!alertType.equals(nPhone)) {
					log.setPhone(alertType + " --> " + nPhone);
					arg22 = true;
				}

				if (!type.equals(nEmail)) {
					log.setEmail(type + " --> " + nEmail);
					arg22 = true;
				}

				if (!continueFlag.equals(nAddress)) {
					log.setAddress(continueFlag + " --> " + nAddress);
					arg22 = true;
				}

				oldContList = this.establishmentContactDao.getList(obj.getId());
			}

			this.establishmentDao.update(obj);
			if (!oldSuperiorIdStr.equals(superiorIdStr)) {
				List arg24 = this.establishmentDao.getAllChildren(obj.getId());
				alertType = "";
				if (oldSuperiorIdStr.equals("")) {
					alertType = ";" + obj.getId() + ";";
				} else {
					alertType = oldSuperiorIdStr + obj.getId() + ";";
				}

				type = "";
				if (superiorIdStr.equals("")) {
					type = ";" + obj.getId() + ";";
				} else {
					type = superiorIdStr + obj.getId() + ";";
				}

				for (int arg29 = 0; arg29 < arg24.size(); ++arg29) {
					Establishment arg26 = (Establishment) arg24.get(arg29);
					arg26.setSuperiorIdStr(arg26.getSuperiorIdStr().replaceAll(
							alertType, type));
					this.establishmentDao.update(arg26);
				}
			}

			alertMsg = "修改成功！";
		} else {
			obj.setId(this.idGenerator.getId(Establishment.class.getName()));
			if (!form.getCodeRule().getGenerateRule().equals("MANUAL")) {
				obj.setEstCode(PageHelper.generateCode(this.serialNumberDao,
						form.getCodeRule(), "", 0L));

				for (Establishment conChangeStr = this.establishmentDao
						.getByEstCode(obj.getEstCode(), obj.getEstType()); conChangeStr != null; conChangeStr = this.establishmentDao
						.getByEstCode(obj.getEstCode(), obj.getEstType())) {
					obj.setEstCode(PageHelper.generateCode(
							this.serialNumberDao, form.getCodeRule(), "", 0L));
				}
			}

			this.establishmentDao.save(obj);
			alertMsg = "增加成功！";
		}

		String arg25 = this.saveContacts(obj.getId(), form.getContacts(),
				(List) oldContList);
		if (!arg25.equals("")) {
			log.setContact(arg25);
			arg22 = true;
		}

		if (arg22) {
			UserBean arg27 = EncCommonHelper.getCurrentUserAccount(request);
			log.setId(this.idGenerator.getId(EstablishmentLog.class.getName()));
			log.setEstId(obj.getId());
			log.setModifierId(arg27.getStaffer().getId());
			log.setModifierName(arg27.getStaffer().getStafferName());
			this.establishmentDao.save(log);
		}

		alertType = request.getParameter("alert_type");
		if (alertType == null) {
			alertType = "";
		}

		type = request.getParameter("type");
		if (type == null) {
			type = "";
		}

		continueFlag = request.getParameter("continue_flag");
		ModelAndView arg28;
		if (continueFlag != null && continueFlag.equals("1")) {
			arg28 = new ModelAndView(
					"redirect:/base/EstablishmentNew.ihtm?type=" + type
							+ "&alert_type=" + alertType);
			EncCommonHelper.setAlertMessage(request, alertMsg);
		} else {
			arg28 = new ModelAndView(this.getSuccessView());
			arg28.addObject("returnValue", String.valueOf(obj.getId()));
			if (alertType == null || !alertType.equals("NONE")) {
				EncCommonHelper.setAlertMessage(request, alertMsg);
			}
		}

		arg28.addObject("alertType", alertType);
		return arg28;
	}

	private String saveContacts(long estId, List contacts, List oldContacts) {
		String changeStr = "";

		for (int i = 0; i < contacts.size(); ++i) {
			EstablishmentContactBean bean = (EstablishmentContactBean) contacts
					.get(i);
			bean.getEstablishmentContact().setEstId(estId);
			if (bean.getStatus().equals("DELETE")) {
				if (bean.getEstablishmentContact().getId() != 0L) {
					this.establishmentContactDao.delete(bean
							.getEstablishmentContact().getId());
				}
			} else if (!bean.getStatus().equals("EDIT")) {
				if (bean.getStatus().equals("NEW")) {
					bean.getEstablishmentContact().setId(
							this.idGenerator.getId(EstablishmentContact.class
									.getName()));
					this.establishmentContactDao.save(bean
							.getEstablishmentContact());
				}
			} else {
				for (int j = 0; j < oldContacts.size(); ++j) {
					EstablishmentContact oc = (EstablishmentContact) oldContacts
							.get(j);
					if (oc.getId() == bean.getEstablishmentContact().getId()) {
						String oName = "";
						String nName = "";
						String oPhone = "";
						String nPhone = "";
						String oMobile = "";
						String nMobile = "";
						if (oc.getContactName() != null) {
							oName = oc.getContactName();
						}

						if (bean.getEstablishmentContact().getContactName() != null) {
							nName = bean.getEstablishmentContact()
									.getContactName();
						}

						if (oc.getPhone() != null) {
							oPhone = oc.getPhone();
						}

						if (bean.getEstablishmentContact().getPhone() != null) {
							nPhone = bean.getEstablishmentContact().getPhone();
						}

						if (oc.getMobile() != null) {
							oMobile = oc.getMobile();
						}

						if (bean.getEstablishmentContact().getMobile() != null) {
							nMobile = bean.getEstablishmentContact()
									.getMobile();
						}

						if (!oName.equals(nName) || !oPhone.equals(nPhone)
								|| !oMobile.equals(nMobile)) {
							if (!changeStr.equals("")) {
								changeStr = changeStr + "\n";
							}

							changeStr = changeStr + oName + " " + oPhone + " "
									+ oMobile + " --> " + nName + " " + nPhone
									+ " " + nMobile;
						}
						break;
					}
				}

				this.establishmentContactDao.update(bean
						.getEstablishmentContact());
			}
		}

		return changeStr;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public EstablishmentDao getEstablishmentDao() {
		return this.establishmentDao;
	}

	public void setEstablishmentDao(EstablishmentDao establishmentDao) {
		this.establishmentDao = establishmentDao;
	}

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public AreaDao getAreaDao() {
		return this.areaDao;
	}

	public void setAreaDao(AreaDao areaDao) {
		this.areaDao = areaDao;
	}

	public EstablishmentContactDao getEstablishmentContactDao() {
		return this.establishmentContactDao;
	}

	public void setEstablishmentContactDao(
			EstablishmentContactDao establishmentContactDao) {
		this.establishmentContactDao = establishmentContactDao;
	}

	public EstablishmentLevelDao getEstablishmentLevelDao() {
		return this.establishmentLevelDao;
	}

	public void setEstablishmentLevelDao(
			EstablishmentLevelDao establishmentLevelDao) {
		this.establishmentLevelDao = establishmentLevelDao;
	}

	public EstablishmentTypeDao getEstablishmentTypeDao() {
		return this.establishmentTypeDao;
	}

	public void setEstablishmentTypeDao(
			EstablishmentTypeDao establishmentTypeDao) {
		this.establishmentTypeDao = establishmentTypeDao;
	}
}